package com.qf.smsplatform.gateway.mq;

import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.gateway.netty4.NettyClient;
import com.qf.smsplatform.gateway.netty4.Utils.Command;
import com.qf.smsplatform.gateway.netty4.Utils.MsgUtils;
import com.qf.smsplatform.gateway.netty4.entity.CmppMessageHeader;
import com.qf.smsplatform.gateway.netty4.entity.CmppSubmit;
import com.qf.smsplatform.gateway.netty4.entity.ControlWindow;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ReceiveSmsFromMq {

    @Autowired
    private NettyClient nettyClient;


    /**
     * 消息接受  并发消费
     *
     */
    @RabbitListener(queues = "${gateway.sendtopic}", containerFactory = "pointTaskContainerFactory")
    public void receive(StandardSubmit submit, Channel channel, Message message) throws IOException, InterruptedException {
        Thread.sleep(10);
        log.info("接收消息:{}",submit);                     // submit也是存储到ES中的日志 , doc_id
        String mobile=submit.getDestMobile();               // 获取目标手机号
        String content=submit.getMessageContent();          // 获取短信内容
        String srcNumber = submit.getSrcNumber();           // 下发源号码
        int sequenceId = MsgUtils.getSequence();            // 在网关模块封装,不迟,但是,推荐在接口模块封装
        submit.setSequenceId(sequenceId + "");        //将sequenceId封装到submit对象中
        CmppMessageHeader submitMessage=new CmppSubmit(Command.CMPP2_VERSION, "", srcNumber, sequenceId, mobile, content); // 封装运营商需要的Message信息
        ControlWindow controlWindow = ControlWindow.getInstance();        // 临时存储submit的位置.(内存)
        log.info("enter window seqID:{},submit:{}",sequenceId,submit);
        controlWindow.put(sequenceId,submit);                           // 存的key就是生成的sequenceId,value就是submit对象
        nettyClient.submit(submitMessage);                  // 将封装好的submitMessage发送给运营商

        //消费MQ消息并手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}
